<?php
namespace console\controllers;

use yii\console\Controller;

class RollbackController extends Controller
{
    public function actionIndex($rollbackDir){
        $rollbackFiles = $onlineFiles = [];
        $rollbackMigrateDir = $rollbackDir.DIRECTORY_SEPARATOR.'console'.DIRECTORY_SEPARATOR.'migrations';

        if(!file_exists($rollbackMigrateDir)){
            exit;
        }
        $rollbackFiles = $this->openDirandGetfiles($rollbackMigrateDir);
        $onlineFiles = $this->openDirandGetfiles(dirname(__DIR__).'/migrations');
        $files = array_diff($onlineFiles,$rollbackFiles);
        $fileCount = count($files);
        $filedir = dirname(dirname(__DIR__));
        $server_name = \Yii::$app->params['swooleTaskName'];
        if($server_name == "dmdswoole_test"){
            shell_exec("$filedir/yii_test migrate/down $fileCount");
        }else{
            shell_exec("$filedir/yii migrate/down $fileCount");
        }

    }

    private function openDirandGetfiles($dir){
        $files = [];
        if ( $handle  =  opendir ( $dir)) {
            while ( false  !== ( $file  =  readdir ( $handle ))) {
                if ( $file  !=  "."  &&  $file  !=  ".." ) {
                    $files[] = $file;
                }
            }
            closedir ( $handle );
        }
        return $files;
    }


}